import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: '', // 使用相对路径，通过nginx代理
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 统一错误处理
    console.error('API请求错误:', error);
    if (error.response) {
      switch (error.response.status) {
        case 400:
          return Promise.reject(new Error('请求参数错误'));
        case 401:
          return Promise.reject(new Error('未授权，请重新登录'));
        case 403:
          return Promise.reject(new Error('拒绝访问'));
        case 404:
          return Promise.reject(new Error('请求的资源不存在'));
        case 500:
          return Promise.reject(new Error('服务器内部错误'));
        default:
          return Promise.reject(new Error('请求失败，请稍后重试'));
      }
    } else if (error.request) {
      return Promise.reject(new Error('网络错误，请检查网络连接'));
    } else {
      return Promise.reject(new Error('请求配置错误'));
    }
  }
);

/**
 * 定义API响应类型
 */
export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
}

// 定义流式响应数据类型
interface StreamChunk {
  type: string;
  content?: string;
  tool?: string;
  success?: boolean;
  data?: any;
  message?: string;
}

// 发送聊天消息 - 流式版本
export const sendChatMessageStream = (messages: any[], onChunk: (chunk: StreamChunk) => void, onComplete: () => void, onError: (error: string) => void): AbortController => {
  const controller = new AbortController();
  const { signal } = controller;
  
  // 直接使用SSE模式，避免WebSocket连接错误
  console.log('使用SSE模式发送流式请求');
    const sseUrl = '/chatMessage';
    const xhr = new XMLHttpRequest();
    
    // 添加取消信号支持
    if (signal) {
      signal.addEventListener('abort', () => {
        xhr.abort();
      });
    }
    
    xhr.open('POST', sseUrl);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.responseType = 'text';
    
    let buffer = '';
    let isCompleted = false;
    
    xhr.onprogress = (event) => {
      if (event.currentTarget && (event.currentTarget as XMLHttpRequest).response) {
        const response = (event.currentTarget as XMLHttpRequest).response;
        const newData = response.substring(buffer.length);
        buffer = response;
        
        // 处理SSE数据流
        const lines = newData.split('\n');
        lines.forEach((line: string) => {
          const trimmedLine = line.trim();
          if (trimmedLine.startsWith('data:')) {
            const dataPart = trimmedLine.substring(5).trim();
            if (dataPart && dataPart !== '') {
              try {
                const data = JSON.parse(dataPart);
                console.log('解析SSE数据:', data);
                
                // 检查是否是结束信号
                if (data.type === 'end') {
                  isCompleted = true;
                  onComplete();
                  return;
                } else if (data.type === 'error') {
                  onError(data.message || '服务器返回错误');
                  return;
                } else if (data.type === 'tool_result') {
                  // 处理工具调用结果
                  onChunk({
                    type: 'tool_result',
                    tool: data.tool,
                    success: data.success,
                    data: data.data,
                    message: data.message
                  } as StreamChunk);
                  return;
                } else {
                  onChunk(data);
                }
              } catch (parseError) {
                console.error('解析SSE数据失败:', parseError, '原始数据:', dataPart);
              }
            }
          }
        });
      }
    };
    
    xhr.onload = () => {
      // 如果已经通过SSE的end信号完成，就不再重复调用
      if (!isCompleted) {
        // 对于SSE流式响应，即使状态码不是200，也可能是正常完成
        if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 400)) {
          onComplete();
        } else {
          onError(`请求失败: ${xhr.status} ${xhr.statusText}`);
        }
      }
    };
    
    xhr.onerror = () => {
      onError('网络错误');
    };
    
    xhr.onabort = () => {
      console.log('请求被取消');
    };
    
    xhr.send(JSON.stringify({ chatMessage: messages }));
  
  return controller;
};

// 保留原有接口以兼容旧代码
export const sendChatMessage = async (messages: any[]): Promise<ApiResponse> => {
  return new Promise((resolve) => {
    let fullContent = '';
    let isComplete = false;
    
    const onChunk = (chunk: { type: string; content?: string }) => {
      if (chunk.type === 'text' && chunk.content) {
        fullContent += chunk.content;
      } else if (chunk.type === 'error') {
        resolve({
          success: false,
          message: chunk.content || '请求失败'
        });
      }
    };
    
    const onComplete = () => {
      if (!isComplete) {
        isComplete = true;
        resolve({
          success: true,
          data: {
            content: fullContent
          }
        });
      }
    };
    
    const onError = (error: string) => {
      if (!isComplete) {
        isComplete = true;
        resolve({
          success: false,
          message: error
        });
      }
    };
    
    sendChatMessageStream(messages, onChunk, onComplete, onError);
  });
};

export default api;